package com.weilai.common.servlet;

import com.weilai.common.model.SysUser;
import net.sf.json.JSONObject;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

/**
 * Created by Song on 2017/6/22.
 */
public class CallBackServlet extends HttpServlet {
    private String dbUrl;
    private String driverName;
    private String username;
    private String password;
    private Connection connection;
    private PreparedStatement preparedStatement;
    private ResultSet resultSet;

    @Override
    public void init(ServletConfig config) throws ServletException {
        this.driverName = config.getInitParameter("driverName");
        this.dbUrl = config.getInitParameter("dbUrl");
        this.username = config.getInitParameter("username");
        this.password = config.getInitParameter("password");
        super.init(config);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String code = req.getParameter("code");

        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ AuthUtil.APPID +
                "&secret="+AuthUtil.APPSECRET +
                "&code=" +code+
                "&grant_type=authorization_code";
        JSONObject jsonObject = AuthUtil.doGetJson(requestUrl);
        String  openid = jsonObject.getString("openid");
        String  token = jsonObject.getString("access_token");
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+token +
                "&openid="+openid;
        JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
        try {
            SysUser user1 = getUser(userInfo.getString("openid"));
            if(!"".equals(user1.getName())){
                //绑定成功
                //跳转到首页
                SysUser user = new SysUser();
                user.setId(user1.getId());
                req.getSession().setAttribute("user",user);
                req.getRequestDispatcher("/index.html").forward(req,resp);
            }else{
                //跳转到登录界面
                //未绑定
                req.setAttribute("openid",openid);
                req.getRequestDispatcher("/bind.jsp").forward(req,resp);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println(userInfo);
        super.doGet(req, resp);
    }

    //根据openid登陆
    public SysUser getUser(String openid) throws SQLException {
        SysUser user = null;
        connection = DriverManager.getConnection(dbUrl,username,password);
        String sql = "select id,`name` from sys_user where openid = ?";
        preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,openid);
        resultSet = preparedStatement.executeQuery();
        while (resultSet.next()){
            user = new SysUser();
            int id = resultSet.getInt(1);
            user.setId(id);
            user.setName(resultSet.getString(2));
        }
        resultSet.close();
        preparedStatement.close();
        connection.close();
        return user;
    }

    //将用户信息添加到数据库
    public void addUserInfo(String openid,String mobileNumber,String pwd) throws SQLException {
        try {
            connection = DriverManager.getConnection(dbUrl,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String sql = "insert into sys_user(moblie_number,pwd,openid) VALUES (?,?,?)";
        preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,mobileNumber);
        preparedStatement.setString(2,pwd);
        preparedStatement.setString(3,openid);
        preparedStatement.execute();
        preparedStatement.close();
        connection.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String mobileNumber = req.getParameter("mobileNumber");
        String pwd = req.getParameter("pwd");
        String openid = req.getParameter("openid");
        try {
            addUserInfo(openid,mobileNumber,pwd);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        super.doPost(req, resp);
    }
}
